/**
 * Created by lixinghan on 2016/11/11.
 */

var http = require('http');
var fs = require('fs');
var server = http.createServer(httpRequest);
var mime = require('mime');

function httpRequest(request,resport){
    var filePath = '';
    if(request.url == '/'){
        filePath = __dirname + '/public/index.html';
    }else{
        filePath = __dirname + '/public/' + request.url;
    }
    readFile(resport,filePath);
}

function  readFile(resport,filePath){
    fs.exists(filePath,function(exists){
       if(exists){
           fs.readFile(filePath,function(error,data){
              if(error){
                  return;
              }
               resport.writeHead(200,{'Content-type':mime.lookup(filePath)});
               resport.end(data);
           });
       }else {
           resport.writeHead(404,{'Content-type':'text/plain'});
           resport.end('sorry!');
       }
    });
}

server.listen(8080,function(){
    console.log('服务器启动成功!');
});